package com.basker.pisces.core.query.factory;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.basker.pisces.core.enums.AggregateType;
import com.basker.pisces.core.query.QueryInfo;
import com.basker.pisces.core.query.builder.QueryBuilder;
import com.basker.pisces.core.query.meta.QueryMeta;

@Component
class AggregateQueryInfoFactory extends QueryInfoFactory<AggregateQueryInfo> {

    @Override
    public QueryInfo create(QueryMeta queryMeta, AggregateQueryInfo aggregateQueryInfo) {
        QueryBuilder builder = QueryBuilder.create(queryMeta);

        builder.setSelectReferenceFields(aggregateQueryInfo.isSelectReferenceFields());

        this.addAggregateFields(aggregateQueryInfo, builder);
        this.addConditions(aggregateQueryInfo.getConditions(), builder);
        this.addOrders(aggregateQueryInfo.getOrders(), builder);

        return builder.buildQueryInfo();
    }

    private void addAggregateFields(AggregateQueryInfo aggregateQueryInfo, QueryBuilder builder) {
        Map<AggregateType, List<String>> aggregateFields = aggregateQueryInfo.getAggregateFields();
        if (CollectionUtils.isEmpty(aggregateFields)) {
            throw new RuntimeException("AggregateQueryInfo has no aggregateFields");
        }

        for (Entry<AggregateType, List<String>> entry : aggregateFields.entrySet()) {
            AggregateType type = entry.getKey();
            List<String> fields = entry.getValue();

            builder.aggregate(type, fields.toArray(new String[fields.size()]));
        }
    }

}
